
import { QueryString } from './tools';
import HttpService from '../service/baseHttp'


function canvasImg(src, callback) {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    const img = new Image();
    img.onload = function () {
        canvas.width = this.width;
        canvas.height = this.height;
        context.drawImage(img, 0, 0);
        const opts = canvasImg.getFileName(src);
        var dataURL = canvas.toDataURL(`image/${opts.ext}`);
        callback(dataURL, { fileName: opts.fileName, type: 'url' });
    }
    // img.setAttribute("crossOrigin", 'anonymous');//同源
    img.src = src;
}
canvasImg.getFileName = function (src) {
    src = decodeURI(src);
    let index = src.lastIndexOf('/') + 1;
    let fileName = src.substring(index)
    //把参数和文件名分割开
    fileName = fileName.split("?")[0];
    const extIndex = fileName.lastIndexOf('.') + 1;
    return {
        fileName,
        name: extIndex && fileName.substring(0, extIndex),
        ext: extIndex && fileName.substring(extIndex) || "jpeg",
    };
}
export default class Webfs {
    static download(data, formdata = {}, options) {
        if (typeof options !== "object" || options === null) options = {};
        const type = options.type || 'form';
        if (type === 'form') {
            const { method = "GET", target } = options;
            if (!method) throw new Error('原始form表单下载，method属性不能为空！');
            const fragment = document.createDocumentFragment();
            const form = document.createElement("form");
            // const iframe = document.createElement("iframe");
            // const iframeId = 'frame' + Date.now();
            // if (!target) {
            //     iframe.style.display = 'none';
            //     iframe.name = iframeId;
            //     iframe.onload = function () {
            //         clearTimeout(this._timeout);
            //         this._timeout = setTimeout(() => {
            //             document.body.removeChild(this);
            //         }, 30000)
            //     }
            // }
            form.style.display = "none";
            form.method = method;
            form.action = data;
            form.target = target || '_blank';
            formdata = QueryString.serialize(formdata || {});
            formdata.forEach(function (item) {
                const input = document.createElement("input");
                input.name = item[0];
                input.value = item[1];
                input.type = "hidden";
                form.appendChild(input);
            })
            // iframe.appendChild(form);
            fragment.appendChild(form);
            document.body.appendChild(fragment);
            form.submit();
            document.body.removeChild(form);
            return;
        }
        if (type === 'url') {
            const link = document.createElement('a'),
                { fileName } = options;
            // if (!('download' in link)) return false;
            link.download = fileName ? fileName : '';
            link.target = '_blank';
            link.style.display = 'none';
            link.href = data;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            return;
        }
        if (type === 'canvas') {
            canvasImg(data, Webfs.download)
            return;
        }
        if ((type === 'binary' || type === 'blob' || type === 'file') && window.URL) {
            const { filetype, fileName } = options;
            // if(!filetype) throw new Error('二进制文件，请配置正确的文件类型（filetype）');
            const blob = data instanceof Blob ? data : new Blob([data], { type: filetype || data.type || "" }),
                base64 = URL.createObjectURL(blob), status = Webfs.download(base64, {}, { ...options, type: 'url' });
            URL.revokeObjectURL(base64);
            if (status === false) navigator.msSaveBlob(blob, fileName);
        }
    }

    static print(data, options) {
        if (typeof options !== "object" || options === null) options = {};
        const { filetype, type = 'url' } = options;
        if (type === 'url') return window.top.open(data, '_blank');
        if (type === 'html') {
            const oWin = window.top.open('about:blank', '_blank');
            oWin.document.write(data);
            return oWin;
        }
        if ((type === 'binary' || type === 'blob' || type === 'file') && window.URL) {
            // if(!filetype) throw new Error('二进制文件，请配置正确的文件类型（filetype）');
            const blob = new Blob([data], { type: filetype || data.type || "" });
            return window.top.open(URL.createObjectURL(blob), '_blank');
        }
    }

    static request(request, formdata = {}, options) {
        if (typeof options !== "object" || options === null) options = { method: 'get', fileType: "application/pdf" };
        const method = (options.method || 'get').toLowerCase(),
            responseType = options.responseType || 'blob';
        return new Promise(function (resolve, reject) {
            const params = method === 'get' ? [{ params: formdata, responseType, headers: options.headers }] : [formdata, { responseType, headers: options.headers }];
            const HttpRequest = typeof request === 'function' ? request(formdata, { responseType, headers: options.headers }) : HttpService[method](request, ...params);
            HttpRequest.then(function (res) {
                let fileName;
                if (typeof options.interceptResponse === 'function') {
                    res = options.interceptResponse(res);
                }
                try {
                    fileName = res.fileName;
                } catch (err) {
                    console.error(err)
                }
                if (options.download) Webfs.download(res, {}, { type: 'blob', fileName, ...options });
                if (options.print) Webfs.print(res, { type: 'blob', fileName, ...options });
                console.log(res)
                resolve(res);
            }).catch(function (err) {
                if (err instanceof Blob) {
                    const reader = new FileReader();
                    reader.readAsText(err);
                    reader.onload = function (e) {
                        reject(JSON.parse(this.result));
                    };
                }
                else if (err.originResponse && err.originResponse.data instanceof Blob) {
                    const reader = new FileReader();
                    reader.readAsText(err.originResponse.data);
                    reader.onload = function (e) {
                        reject(JSON.parse(this.result));
                    };
                } 
                else {
                    console.log(err,'e2');
                }
            });
        })

    }
}
